<template>
	<div class="system-user-container">
		<el-row>
			<el-col :xs="24" :sm="4">
				<el-card shadow="hover" class="mr10 h100">
					<el-collapse v-model="accordion.active" accordion>
						<el-collapse-item name="deptUser">
							<template #title> <i class="fa fa-address-book-o"></i><span class="ml10">部门用户</span></template>
							<el-tree :data="tree.dept.datas" :props="tree.dept.props" highlight-current="true" @node-click="deptTreeNodeClick"></el-tree>
						</el-collapse-item>
						<el-collapse-item name="roleUser">
							<template #title> <i class="fa fa-user-circle"></i><span class="ml10">角色用户</span></template>
							<el-tree :data="tree.role.datas" :props="tree.role.props" highlight-current="true" @node-click="roleTreeNodeClick"></el-tree>
						</el-collapse-item>
						<el-collapse-item name="postUser">
							<template #title> <i class="fa fa-user-circle-o"></i><span class="ml10">岗位用户</span></template>
							<el-tree :data="tree.post.datas" :props="tree.post.props" highlight-current="true" @node-click="postTreeNodeClick"></el-tree>
						</el-collapse-item>
						<el-collapse-item name="rankUser">
							<template #title> <i class="fa fa-user-secret"></i><span class="ml10">职级用户</span></template>
							<el-tree :data="tree.rank.datas" :props="tree.rank.props" highlight-current="true" @node-click="rankTreeNodeClick"></el-tree>
						</el-collapse-item>
						<el-collapse-item name="groupUser">
							<template #title> <i class="fa fa-user-md"></i><span class="ml10">群组用户</span></template>
							<el-tree :data="tree.group.datas" :props="tree.group.props" highlight-current="true" @node-click="groupTreeNodeClick"></el-tree>
						</el-collapse-item>
					</el-collapse>
				</el-card>
			</el-col>
			<el-col :xs="24" :sm="20">
				<el-card shadow="hover" class="mb10" v-auth="'system:user:list'">
					<el-input size="small" v-model="search.loginName" placeholder="请输入登录账号" prefix-icon="el-icon-search" style="max-width: 180px;" class="ml10"></el-input>
					<el-input size="small" v-model="search.userName" placeholder="请输入用户名称" prefix-icon="el-icon-search" style="max-width: 180px;" class="ml10"></el-input>
					<el-input size="small" v-model="search.phone" placeholder="请输入手机号码" prefix-icon="el-icon-search" style="max-width: 180px;" class="ml10"></el-input>
					<el-input size="small" v-model="search.email" placeholder="请输入邮箱账号" prefix-icon="el-icon-search" style="max-width: 180px;" class="ml10"></el-input>
					<el-date-picker size="small" type="daterange" align="right" v-model="dateData.value" :shortcuts="dateData.shortcuts" 
						unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" class="ml10"></el-date-picker>
					<el-button size="small" icon="el-icon-search" type="primary" class="ml10" @click="onTableSearch()">查询</el-button>
					<el-button size="small" icon="el-icon-refresh" @click="onResetSearch()">重置</el-button>
				</el-card>
				<el-card shadow="hover">
					<el-button v-auth="'system:user:add'" size="small" type="primary" class="ml10" icon="el-icon-document-add" @click="onOpenAddUser()">新增</el-button>
					<el-button v-auth="'system:user:edit'" size="small" type="primary" class="ml10" icon="el-icon-edit" @click="onOpenEditUser()" :disabled="tableData.selections.length != 1">修改</el-button>
					<el-button v-auth="'system:user:remove'" size="small" type="primary" class="ml10" icon="el-icon-delete" @click="onTabelRowsDel()" :disabled="tableData.selections.length <= 0">删除</el-button>
					<el-table ref="tableUserRef" :data="tableData.data" @selection-change="onTableSelectionChange" style="width: 100%" row-key="id">
						<el-table-column type="selection" align="cneter" width="50" show-overflow-tooltip></el-table-column>
						<el-table-column type="index" align="cneter" width="50" show-overflow-tooltip></el-table-column>
						<!-- <el-table-column label="头像" width="50" show-overflow-tooltip>
							<template #default="scope">
								<el-image style="width: 30px; height: 30px"
									v-if="scope.row.avatar"
									:src="scope.row.avatar" 
									:preview-src-list="[scope.row.avatar]">
								</el-image>
								<el-image style="width: 30px; height: 30px"
									v-else
									src="/images/profile.png" 
									preview-src-list="['/images/profile.png']">
								</el-image>
							</template>
						</el-table-column> -->
						<el-table-column label="登录账号" prop="loginName" show-overflow-tooltip></el-table-column>
						<el-table-column label="用户名称" prop="userName" show-overflow-tooltip></el-table-column>
						<el-table-column label="性别" prop="sex" width="50" show-overflow-tooltip>
							<template #default="scope">
								<span v-if="scope.row.sex == '0'" class="color-primary">男</span>
								<span v-else-if="scope.row.sex == '1'" class="color-success">女</span>
								<span v-else class="color-info">未知</span>
							</template>
						</el-table-column>
						<el-table-column label="手机号码" prop="phone" width="120" show-overflow-tooltip></el-table-column>
						<el-table-column label="邮箱账号" prop="email" width="120" show-overflow-tooltip></el-table-column>
						<el-table-column label="状态" show-overflow-tooltip width="70">
							<template #default="scope">
								<span v-if="scope.row.status == '0'" class="color-primary">正常</span>
								<span v-else-if="scope.row.status == '1'" class="color-info">停用</span>
								<span v-else class="color-danger">删除</span>
							</template>
						</el-table-column>
						<!-- <el-table-column label="备注" prop="remark" show-overflow-tooltip></el-table-column> -->
						<el-table-column label="创建时间" prop="createTime" width="180" show-overflow-tooltip></el-table-column>
						<el-table-column label="操作" show-overflow-tooltip width="155"
							v-auths="['system:user:resetPwd', 'system:user:edit', 'system:user:remove']">
							<template #default="scope">
								<el-button v-auth="'system:user:resetPwd'" size="mini" type="text" @click="onOpenResetPwd(scope.row)">密码重置</el-button>
								<el-button v-auth="'system:user:edit'" size="mini" type="text" @click="onOpenEditUser(scope.row)">修改</el-button>
								<el-button v-auth="'system:user:remove'" size="mini" type="text" :disabled="scope.row.isAdmin == 'Y'" @click="onTabelRowDel(scope.row)">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
					<el-pagination
						@size-change="onPageSizeChange"
						@current-change="onPageCurrentChange"
						class="mt15"
						:pager-count="5"
						:page-sizes="[10, 20, 30, 40, 50, 60]"
						v-model:current-page="search.pageNum"
						background
						v-model:page-size="search.pageSize"
						layout="total, sizes, prev, pager, next, jumper"
						:total="tableData.total"
					>
					</el-pagination>
				</el-card>
				<AddUser ref="addUserRef" @submit="onTableSearch"/>
				<EditUser ref="editUserRef" @submit="onTableSearch"/>
				<ResetPwd ref="resetPwdRef" @submit="onTableSearch"/>
			</el-col>
		</el-row>
	</div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import AddUser from '/@/views/system/user/addUser.vue';
import EditUser from '/@/views/system/user/editUser.vue';
import ResetPwd from '/@/views/system/user/resetPwd.vue';
import { getUserList, delUser } from '/@/api/system/user/index';
import { getDeptList } from '/@/api/system/dept/index';
import { getRoleList } from '/@/api/system/role/index';
import { getPostList } from '/@/api/system/post/index';
import { getRankList } from '/@/api/system/rank/index';
import { getGroupList } from '/@/api/system/group/index';
import { lineToTreeData } from '/@/utils/commonFunction';
import { formatDate, getDateRangeShortcuts } from '/@/utils/formatTime';
export default {
	name: 'user',
	components: { AddUser, EditUser, ResetPwd },
	setup() {
		const tableUserRef = ref();
		const addUserRef = ref();
		const editUserRef = ref();
		const resetPwdRef = ref();
		const state = reactive({
			accordion: {
				active: 'deptUser'
			},
			tree: {
				dept:{
					datas: [],
					props: {
						label: 'deptName',
						children: 'children'
					}
				},
				role:{
					datas: [],
					props: {
						label: 'roleName',
						children: 'children'
					}
				},
				post:{
					datas: [],
					props: {
						label: 'postName',
						children: 'children'
					}
				},
				rank:{
					datas: [],
					props: {
						label: 'rankName',
						children: 'children'
					}
				},
				group:{
					datas: [],
					props: {
						label: 'groupName',
						children: 'children'
					}
				}
			},
			search: {
				deptId: '',
				roleIds: '',
				postIds: '',
				rankIds: '',
				groupIds: '',
				allocated: 'Y',//已分配的用户
				loginName: '',
				userName: '',
				phone: '',
				email: '',
				startTime: '',
				endTime: '',
				orderBy: 'createTime',
				isAsc: 'desc',
				pageNum: 1,
				pageSize: 10
			},
			dateData: {
				value: [],
				shortcuts: getDateRangeShortcuts()
			},
			tableData: {
				selections: [],//选中的行数据
				data: [],
				total: 0,
				loading: false
			}
		});

		const loadDepts = () => {
			getDeptList().then((res) => {
				if(res.code == 0){
					state.tree.dept.datas = lineToTreeData(res.data);
				}
			});
		}

		const loadRoles = () => {
			getRoleList().then((res) => {
				if(res.code == 0){
					state.tree.role.datas = res.data;
				}
			});
		}

		const loadPosts = () => {
			getPostList().then((res) => {
				if(res.code == 0){
					state.tree.post.datas = res.data;
				}
			});
		}
		
		const loadRanks = () => {
			getRankList().then((res) => {
				if(res.code == 0){
					state.tree.rank.datas = res.data;
				}
			});
		}
		
		const loadGroups = () => {
			getGroupList().then((res) => {
				if(res.code == 0){
					state.tree.group.datas = res.data;
				}
			});
		}

		const loadTableData = (params) => {
			getUserList(Object.assign(state.search, params)).then((res) => {
				if(res.code == 0){
					state.tableData.data = res.data;
					state.tableData.total = res.total;
					tableUserRef.value.clearSelection();
				}
			});
		}

		//查询
		const onTableSearch = () => {
			if(state.dateData.value.length == 2){
				state.search.startTime = formatDate(state.dateData.value[0], 'yyyy-MM-dd') + ' 00:00:00';
				state.search.endTime = formatDate(state.dateData.value[1], 'yyyy-MM-dd') + ' 23:59:59';
			}
			loadTableData(state.search);
		}
		//重置
		const onResetSearch = () => {
			state.dateData.value = [];
			state.search.deptId = undefined;
			state.search.roleIds = undefined;
			state.search.postIds = undefined;
			state.search.rankIds = undefined;
			state.search.groupIds = undefined;
			state.search.loginName = undefined;
			state.search.userName = undefined;
			state.search.phone = undefined;
			state.search.email = undefined;
			state.search.startTime = undefined;
			state.search.endTime = undefined;
			state.search.pageNum = 1;
			state.search.pageSize = 10;
			loadTableData(state.search);
		}
		// 监听表格选中行
		const onTableSelectionChange = (selections) =>{
			state.tableData.selections = selections;
		};
		// 每页显示数据大小改变
		const onPageSizeChange = (val: number) => {
			state.search.pageSize = val;
			loadTableData(state.search);
		};
		// 页码改变
		const onPageCurrentChange = (val: number) => {
			state.search.pageNum = val;
			loadTableData(state.search);
		};
		// 打开新增用户弹窗
		const onOpenAddUser = (row: object) => {
			addUserRef.value.openDialog(row);
		};
		// 打开编辑用户弹窗
		const onOpenEditUser = (row: object) => {
			row = row || state.tableData.selections[0];
			editUserRef.value.openDialog(row);
		};
		// 打开重置密码弹窗
		const onOpenResetPwd = (row: object) => {
			resetPwdRef.value.openDialog(row);
		};
		// 删除选中行
		const onTabelRowsDel = () => {
			const ids = state.tableData.selections.map(item => item.id);
			if(ids && ids.length > 0){
				ElMessageBox.confirm('确定删除选中的用户信息吗？', '提示', {
					confirmButtonText: '删除',
					cancelButtonText: '取消',
					type: 'warning',
				}).then(() => {
					delUser(ids).then((res) => {
						if(res.code === 0){
							ElMessage.success('删除成功');
							loadTableData();
						}
					});
				}).catch(() => {});
			}
		};
		// 删除当前行
		const onTabelRowDel = (row: object) => {
			ElMessageBox.confirm('确定删除该条【' + row.userName + '】用户信息吗？', '提示', {
				confirmButtonText: '删除',
				cancelButtonText: '取消',
				type: 'warning',
			}).then(() => {
				delUser([row.id]).then((res) => {
					if(res.code === 0){
						ElMessage.success('删除成功');
						loadTableData();
					}
				});
			}).catch(() => {});
		};
		//点击部门树
		const deptTreeNodeClick = (node) => {
			state.search.deptId = node.id;
			state.search.roleIds = '';
			state.search.postIds = '';
			state.search.rankIds = '';
			state.search.groupIds = '';
			onTableSearch();
		}
		//点击角色树
		const roleTreeNodeClick = (node) => {
			state.search.deptId = '';
			state.search.roleIds = node.id;
			state.search.postIds = '';
			state.search.rankIds = '';
			state.search.groupIds = '';
			onTableSearch();
		}
		//点击岗位树
		const postTreeNodeClick = (node) => {
			state.search.deptId = '';
			state.search.roleIds = '';
			state.search.postIds = node.id;
			state.search.rankIds = '';
			state.search.groupIds = '';
			onTableSearch();
		}
		//点击职级树
		const rankTreeNodeClick = (node) => {
			state.search.deptId = '';
			state.search.roleIds = '';
			state.search.postIds = '';
			state.search.rankIds = node.id;
			state.search.groupIds = '';
			onTableSearch();
		}
		//点击群组树
		const groupTreeNodeClick = (node) => {
			state.search.deptId = '';
			state.search.roleIds = '';
			state.search.postIds = '';
			state.search.rankIds = '';
			state.search.groupIds = node.id;
			onTableSearch();
		}
		// 页面加载时
		onMounted(() => {
			loadDepts();
			loadRoles();
			loadPosts();
			loadRanks();
			loadGroups();
			loadTableData();
		});
		return {
			tableUserRef,
			addUserRef,
			editUserRef,
			resetPwdRef,
			onTableSearch,
			onTableSelectionChange,
			onResetSearch,
			onPageSizeChange,
			onPageCurrentChange,
			onOpenAddUser,
			onOpenEditUser,
			onOpenResetPwd,
			onTabelRowsDel,
			onTabelRowDel,
			deptTreeNodeClick,
			roleTreeNodeClick,
			postTreeNodeClick,
			rankTreeNodeClick,
			groupTreeNodeClick,
			...toRefs(state),
		};
	},
};
</script>